import { BaseContext } from 'koa'
import { getManager, Repository } from 'typeorm'
import { Project } from '../entity/project'
import { OKBody, FailBody } from '../utils/requests/index'
import { shouldBlock } from '../utils/middleware/parseCtxSession'

export default class UserController {
  public static async getProject(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    const prjId: number = +ctx.params.id
    if (prjId === undefined) throw new Error('projectID不能为空')
    try {
      // 获取用户信息
      const repo: Repository<Project> = getManager().getRepository(Project)
      const data: Project = await repo.findOne({
        id: prjId
      })

      ctx.body = OKBody(data)
    } catch (err) {
      ctx.body = FailBody(err.message)
    }
  }

  public static async getProjectAll(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    try {
      // 获取用户信息
      const repo: Repository<Project> = getManager().getRepository(Project)
      const data: Project[] = await repo.find({
        order: {
          createdTime: 'DESC',
        }
      })

      ctx.body = OKBody(data)
    } catch (err) {
      ctx.body = FailBody(err.message)
    }
  }

  /**
   * 更新项目信息
   * @param ctx Koa Ctx
   */
  public static async updateProject(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    try {
      const repo: Repository<Project> = getManager().getRepository(Project)
      const body = ctx.request.body

      if (body.id === undefined) throw new Error('id不能为空')
      if (body.staticFiles === undefined) throw new Error('staticFiles不能为空')

      const prj: Project = await repo.findOne({
        id: +body.id,
      })

      prj.staticFiles = body.staticFiles

      // send email with token
      const savedPrj = await repo.save(prj)
      ctx.body = OKBody(savedPrj)
    } catch (err) {
      // 处理Email重复
      ctx.body = FailBody(err.message)
    }
  }

  /**
   * 创建项目
   * @param ctx KoaContext
   */
  public static async createProject(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    try {
      const session = ctx.session

      const repo: Repository<Project> = getManager().getRepository(Project)
      const body = ctx.request.body

      const prj: Project = new Project()
      if (!body.title) throw new Error('title字段不能为空')

      prj.userid = session.userid
      prj.userNickname = session.nickname
      // prj.staticFiles = session.staticFiles
      prj.title = body.title
      prj.createdTime = new Date()

      // send email with token
      const createdPrj = await repo.save(prj)

      ctx.body = OKBody(createdPrj)
    } catch (err) {
      // 处理Email重复
      ctx.body = FailBody(err.message)
    }
  }
}
